﻿# -*- coding: utf-8 -*-

"""
PyoCDVD (http://code.google.com/p/pyocdvd/)
Media Organizer (CD, DVD, etc)

Developers:
    Bruno Pitteli Gonçalves <scorninpc(*)gmail(*)com>
    Paul Eipper <lkraider(*)gmail(*)com>

Licence: GNU GENERAL PUBLIC LICENSE v3

"""

try:
    import pygtk
    pygtk.require('2.0')
except:
    pass
import sys
import gtk
import gtk.glade
import dialogs


class PyoCDVD_Interface:
    '''Display the Glade interface and provide interface interaction methods.'''

    def __init__(self, pyocdvd):
        self.dialogs = dialogs.PyoCDVD_Dialogs()
        self.pyocdvd = pyocdvd
        self.widgetTree = gtk.glade.XML('interface/pyocdvd.glade')
        # Get the main window and connect the 'destroy' event
        self.window = self.widgetTree.get_widget('pyocdvd')
        if (self.window):
            self.window.connect('destroy', gtk.main_quit)
        self._connect_widgets()
        # Autoconnect Signals and Callbacks
        self.widgetTree.signal_autoconnect(self)
        self.window.show_all()
        self.append_status_message('PyoCDVD - Python Organizador de CD/DVD')

    def display(self):
        self._populate_main_list(self.pyocdvd.list_all_discs())
        gtk.main()

    # Callbacks
    def on_add_clicked(self, widget):
        '''Open add media pane.'''
        self._swap_notebook_pane(1)
        self._reset_media_pane()

    def on_search_clicked(self, widget):
        '''Search files.'''
        response, query_text = self.dialogs.search_dialog()
        if response:
            lines = self.pyocdvd.search_files(query_text)
            self._populate_main_list(lines)

    def on_back_clicked(self, widget):
        '''Open main pane.'''
        self._swap_notebook_pane(0)
        self._populate_main_list(self.pyocdvd.list_all_discs())

    def on_quit_clicked(self, widget):
        '''Close application.'''
        gtk.main_quit()

    def on_add_tag_clicked(self, widget):
        #TODO: implemente method to add the tag
        print 'on_add_tag_clicked'

    def on_remove_tag_clicked(self, widget):
        #TODO: implemente method to remove the tag
        print 'on_remove_tag_clicked'

    def on_scan_clicked(self, widget):
        '''Scan a device for files.'''
        error_msg, file_list = self.pyocdvd.scan_devices()
        if error_msg:
            self.dialogs.error_dialog(error_msg)
        else:
            for filename in file_list:
               self._append_file(filename)

    def on_addfile_clicked(self, widget):
        '''Manually add a file.'''
        response, filename = self.dialogs.file_input_dialog()
        if response and filename:
            self._append_file(filename)

    def on_clear_clicked(self, widget):
        '''Empty file list.'''
        self.file_list_treeviewStore.clear()

    def on_save_clicked(self, widget):
        '''Save disc data.'''
        disc_name = self.disc_name_entry.get_text()
        comments = self.comments_textviewBuffer.props.text
        file_list = self.file_list_treeviewStore
        error_msg, status_msg = self.pyocdvd.save_disc(disc_name, comments, file_list)
        if error_msg:
            self.dialogs.error_dialog(error_msg)
        else:
            self.append_status_message(status_msg)
            self._reset_media_pane()

    def on_checkbox_toggled(self, cell, path, model):
        '''Toggle selection of the file as to be saved or not.'''
        model[path][0] = not model[path][0]

    # Helper functions
    def append_status_message(self, text):
        self.status_textviewBuffer.props.text += '%s\n' % text
    
    def _swap_notebook_pane(self, page):
        self.notebook.set_current_page(page)
        self.widgetTree.get_widget('add').set_sensitive(not bool(page))
        self.widgetTree.get_widget('back').set_sensitive(bool(page))

    def _populate_main_list(self, lines):
        self.main_treeviewStore.clear()
        for line in lines:
            # TODO: this is a placeholder code while tags are not returned with the disc data
            if len(line) < 5:
                line += (u'',)
            self.main_treeviewStore.append(line)

    def _append_file(self, filename, selected=True):
        self.file_list_treeviewStore.append([selected, filename])

    def _reset_media_pane(self):
        self.disc_name_entry.set_text('')
        self.comments_textviewBuffer.props.text = ''
        self.file_list_treeviewStore.clear()

    def _connect_widgets(self):
        '''Setup the glade widgets as class attributes for easy access.'''
        self.disc_name_entry = self.widgetTree.get_widget('disc_name_entry')
        self.tags_combobox = self.widgetTree.get_widget('tags_combobox')
        self.notebook = self.widgetTree.get_widget('notebook')

        # Status TextView
        self.status_textview = self.widgetTree.get_widget('status_textview')
        self.status_textviewBuffer = gtk.TextBuffer()
        self.status_textview.set_buffer(self.status_textviewBuffer)

        # Comments TextView
        self.comments_textview = self.widgetTree.get_widget('comments_textview')
        self.comments_textviewBuffer = gtk.TextBuffer()
        self.comments_textview.set_buffer(self.comments_textviewBuffer)

        # Main TreeView
        self.main_treeview = self.widgetTree.get_widget('main_treeview')
        self.main_treeviewStore = gtk.ListStore(str, str, str, str, str)
        self.main_treeview.set_model(self.main_treeviewStore)
        columns = ['Código', 'Nome', 'Data','Comentário', 'Marcador']
        min_width = [50, 100, 100, 200, 0]
        for i in range(len(columns)):
            columns[i] = gtk.TreeViewColumn(columns[i], gtk.CellRendererText(), text=i)
            columns[i].set_min_width(min_width[i])
            self.main_treeview.append_column(columns[i])

        # File list TreeView
        self.file_list_treeview = self.widgetTree.get_widget('file_list_treeview')
        self.file_list_treeviewStore = gtk.ListStore(bool, str)
        self.file_list_treeview.set_model(self.file_list_treeviewStore)
        checkbox = gtk.CellRendererToggle()
        checkbox.set_property('activatable', True)
        checkbox.connect('toggled', self.on_checkbox_toggled, self.file_list_treeviewStore)
        column = gtk.TreeViewColumn(None, checkbox, active=0)
        column.set_min_width(30)
        self.file_list_treeview.append_column(column)
        column = gtk.TreeViewColumn('Nome do Arquivo', gtk.CellRendererText(), text=1)
        self.file_list_treeview.append_column(column)